package com.example.win.android_banduyujia.peopleactivity.activity.activity.openactivity.DataActivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.entity.Constants;
import com.example.win.android_banduyujia.entity.LoginInfEntity;
import com.example.win.android_banduyujia.entity.TodayEntity;
import com.example.win.android_banduyujia.http.request.UpdaloadRequest;
import com.example.win.android_banduyujia.http.response.BaseHttpResponse;
import com.example.win.android_banduyujia.lib.util.FileUtils;
import com.example.win.android_banduyujia.login.application.LoginApplication;
import com.example.win.android_banduyujia.peopleactivity.activity.activity.openactivity.AsanapicActivity;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseTitleBarActivity;
import com.example.win.android_banduyujia.ui.time.SlideDateTimeListener;
import com.example.win.android_banduyujia.ui.time.SlideDateTimePicker;
import com.example.win.android_banduyujia.ui.view.CircleImageView;
import com.example.win.android_banduyujia.ui.view.ImageLoader;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Win on 2015/8/14.
 */
public class DataActivity extends BaseTitleBarActivity implements View.OnClickListener {
   public static final String TAG = DataActivity.class.getSimpleName();

    private static final String  RESULT_NAME = "DataActivity.RESULT_NAME";
    private static final String  RESULT_SEX = "DataActivity.RESULT_SEX";
    private static final String  RESULT_FIRST = "DataActivity.RESULT_FIRST";

    private static final int  REQUEST_CODE_NAME = 0x001;
    private static final int  REQUEST_CODE_SEX = 0x002;
    private static final int  REQUEST_CODE_FIRST = 0x003;
    private static final int  REQUEST_CODE_CAMERA = 0x004;

    private LinearLayout   LayoutPhone, LayoutName, LayoutSex, LayoutAddress, LayoutFirst,Layourexce,
                           LayoutPhoto, LayoutScope, LayoutProAddress,LayoutVenues;

    private CircleImageView  mHeaderImageView;
    private TextView  mTvtPhone, mTvtName, mTvtSex, mTvtDate,mTvtFirst,mTvtTime;
    private TextView  mTvtPhoto, mTvtScope,mTvtAdress, mTvtVenues;

    private View   v;
    private String   mImageName = " ";
    private LoginInfEntity  mLoginInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedClosableObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

        setContentView(R.layout.layout_page_data);

        InitTitles();
        loadDatas();
        InitViews();
    }

    private void InitTitles() {
        setTitle(R.string.title_text_view_basic_data);
        showLeftBackButton();
    }

    private void loadDatas() {

    }

    private void InitViews() {
        LayoutPhone = (LinearLayout) findViewById(R.id.linear_layout_info_phone);
        LayoutName = (LinearLayout) findViewById(R.id.linear_layout_info_name);
        LayoutSex = (LinearLayout) findViewById(R.id.linear_layout_info_sex);
        LayoutAddress = (LinearLayout) findViewById(R.id.linear_layout_info_address);
        LayoutFirst = (LinearLayout) findViewById(R.id.linear_layout_info_first);
        LayoutPhoto = (LinearLayout)findViewById(R.id.linear_layout_info_photo);
        LayoutScope = (LinearLayout) findViewById(R.id.linear_layout_info_scope);
        LayoutProAddress = (LinearLayout) findViewById(R.id.linear_layout_info_pro_address);
        LayoutVenues = (LinearLayout) findViewById(R.id.linear_layout_info_venues);
        Layourexce = (LinearLayout) findViewById(R.id.linear_layout_experience);

        mHeaderImageView = (CircleImageView) findViewById(R.id.title_photo_circle_image_view);
        mTvtPhone = (TextView) findViewById(R.id.title_list_item_phone);
        mTvtName = (TextView) findViewById(R.id.title_list_item_name);
        mTvtSex = (TextView) findViewById(R.id.title_list_item_sex);
        mTvtDate = (TextView) findViewById(R.id.title_list_item_datetime);
        mTvtTime = (TextView) findViewById(R.id.textview_title_list_time);
        mTvtFirst = (TextView) findViewById(R.id.title_list_item_first);

        LayoutPhone.setOnClickListener(this);
        LayoutName.setOnClickListener(this);
        LayoutSex.setOnClickListener(this);
        LayoutAddress.setOnClickListener(this);
        LayoutFirst.setOnClickListener(this);
        LayoutPhoto.setOnClickListener(this);
        LayoutScope.setOnClickListener(this);
        LayoutProAddress.setOnClickListener(this);
        LayoutVenues.setOnClickListener(this);
        Layourexce.setOnClickListener(this);

        mHeaderImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new PopupWindows(DataActivity.this, mHeaderImageView);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.linear_layout_info_phone: // 头像
               // CommonUtils.launchActivityForResult(this, PhotoSelectorActivity.class, 0);
               // mTvtPhone.setText(" ");

                break;
            case R.id.linear_layout_info_name: // 姓名
                 UpdateNickNameActivity();
                break;
            case R.id.linear_layout_info_sex:// 性别
                UpdateSexActivity();
                break;
            case R.id.linear_layout_info_address: // 出生日期
                dateTimeActivity();
                break;
            case R.id.linear_layout_info_first: // 教龄
                UpdateFirstActivity();
                break;
            case R.id.linear_layout_experience: // 教学经验
                ExperienceActivity();
                break;
            case R.id.linear_layout_info_photo: // 上传体式图片
                UpdateInfoActivity();
                break;
            case R.id.linear_layout_info_scope: // 授课范围
                UpdateScopeActivity();
                break;
            case R.id.linear_layout_info_pro_address: // 授课区域
                UpdateProAddressActivity();
                break;
            case R.id.linear_layout_info_venues: // 签署场馆
                VenuesActivity();
                break;
        }
    }

    private SimpleDateFormat  mFormatter = new SimpleDateFormat("yyyy MMMM dd");

    private void dateTimeActivity() {
        new SlideDateTimePicker.Builder(getSupportFragmentManager())
                .setListener(listener)
                .setInitialDate(new Date())
                .build()
                .show();
    }

    private SlideDateTimeListener listener = new  SlideDateTimeListener(){

        @Override
        public void onDateTimeSet(Date date) {
            mTvtTime.setText( mFormatter.format(date) );
          //  Toast.makeText(DataActivity.this,mFormatter.format(date), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDateTimeCancel() {
            Toast.makeText(DataActivity.this,"Canceled", Toast.LENGTH_SHORT).show();
        }
    };

    private void UpdateNickNameActivity() {
         /*Intent  intent = new Intent(this, UpdateNameActivity.class);
         startActivityForResult(intent, REQUEST_CODE_NAME);*/
        startActivity(new Intent(this, UpdateNameActivity.class));
    }

    private void UpdateSexActivity() {
        Intent  intent = new Intent(this, UpdateSexActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SEX);
    }

    private void UpdateFirstActivity() {
        Intent  intent = new Intent(this, UpdateFirstActivity.class);
        startActivityForResult(intent, REQUEST_CODE_FIRST);
    }

    private void ExperienceActivity() {
        startActivity(new Intent(this, ExpericenceActivity.class));
    }

    private void UpdateInfoActivity() {
        startActivity(new Intent(this, AsanapicActivity.class));
    }

    private void UpdateScopeActivity() {
        startActivity(new Intent(this, TeachingscopeActivity.class));
    }

    private void UpdateProAddressActivity() {
        startActivity(new Intent(this, TeachAddressActivity.class));
    }

    private void VenuesActivity() {
        startActivity(new Intent(this, VenuessActivity.class));
    }

    private void initDatas() {
        mLoginInfo = LoginApplication.getInstance().getUser();
        if(mLoginInfo == null){
            finish();
        }

        // 头像的问题
        Bitmap  bitmap = ImageLoader.getInstance().getImage(mLoginInfo.getAvatarUrl());
        mHeaderImageView.setImageBitmap(bitmap);

        mTvtName.setText(mLoginInfo.getLoginProfile().getName());
        mTvtSex.setText(Constants.getSexByCode(mLoginInfo.getLoginProfile().getSex()));
        mTvtAdress.setText(mLoginInfo.getLoginProfile().getBirthday());
        mTvtFirst.setText(mLoginInfo.getLoginProfile().getFirst());
    }

    public class PopupWindows extends PopupWindow{

        public PopupWindows(Context mContext, View parent) {
            View view = View.inflate(mContext,R.layout.title_pic_item,null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    picture();
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
          }
        }

    private static final int TAKE_PICTURE = 0x000000;
    private static final int TAKE_PHOTO = 0x000001;
    private static final int TAKE_CROP = 0x000002;
    //private String path = "";

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
    }

    public void photo() {
        String  status = Environment.getExternalStorageState();
        if(status.equals(Environment.MEDIA_MOUNTED)){
            File dir = new File(Environment.getExternalStorageDirectory() + "/image/");
            if(!dir.exists())dir.mkdirs();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), ".jpg")));
           /* File file = new File(dir, String.valueOf(System.currentTimeMillis()) + ".jpg");
            path = file.getPath();
            Uri  imageUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);*/
            intent.putExtra("return-data", true);
          //  intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, TAKE_PICTURE);
        }else{
            Toast.makeText(getApplicationContext(), "没有卡", Toast.LENGTH_LONG).show();
        }
     }

    public void picture() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
       // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, TAKE_PHOTO);
    }

    private static final int REQUEST_CODE_ALBUM = 0X006;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO: // 如果是直接从相册获取
                startPhotoZoom(data.getData());
                break;
            case TAKE_PICTURE: // 如果是调用相机拍照时
                File temp = new File(Environment.getExternalStorageDirectory() + "/.jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            case TAKE_CROP: // 取得裁剪后的图片
                if (data != null) {
                    setPicToView(data);
                }
                break;
            case REQUEST_CODE_ALBUM:
                 saveImage(requestCode);
                break;
        }
    }

    // 裁剪图片方法实现 173 * 174
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
       // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, TAKE_CROP);
    }
    //	保存裁剪之后的图片数据 201 * 202
    public void setPicToView(Intent data) {
        Bundle  exreas = data.getExtras();
        if(exreas !=null){
            Bitmap  photo = exreas.getParcelable("data");
            Drawable  drawable = new BitmapDrawable(photo);

            /* 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，
		       QQ头像上传采用的方法跟这个类似 213 */
            mHeaderImageView.setImageBitmap(photo);
        }
    }

    private String   mImageView= " ";
    private void saveImage(int requestCode) {
        if(FileUtils.exists(Constants.IMAGE_CAPTURE_URI.getPath())){
            String imageName = UUID.randomUUID().toString() + ".jpg";
            //file path 存文件的地址
            String path = Environment.getExternalStorageDirectory().toString() + Constants.PATH_USER_HEADER + imageName;
            FileUtils.fileCpy(Constants.IMAGE_CAPTURE_URI.getPath(), path, true);
            Bitmap bit = BitmapFactory.decodeFile(path);
            if(bit != null){
                mImageView = imageName;
                mHeaderImageView.setImageDrawable(new BitmapDrawable(bit));
                ImageLoader.getInstance().putBitmapIntoMemCache(path, bit);
                mLoginInfo = LoginApplication.getInstance().getUser();
                mLoginInfo.setAvatarUrl(path);
                UpdaloadRequest request = new UpdaloadRequest(LoginApplication.getInstance().getAccessToken());
                request.doRequestFile(DataActivity.this, BaseHttpResponse.class, mCallbackHandler, true,mCallbackHandler, path);
            }else{
                Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
            }

            FileUtils.clearFileInDir(Constants.IMAGE_CAPTURE_URI.getPath());
            if(requestCode == REQUEST_CODE_CAMERA){
                FileUtils.clearFileInDir(Constants.IMAGE_CAPTURE_URI.getPath());
            }
            initDatas();
        }else{
            Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
        }
    }

    private Handler mCallbackHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.v("avatar", "yes");
        }
    };
}
